package cn.jcet.gumall.product.service.impl;

import cn.jcet.gumall.product.service.CategoryBrandRelationService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.jcet.common.utils.PageUtils;
import cn.jcet.common.utils.Query;

import cn.jcet.gumall.product.dao.CategoryDao;
import cn.jcet.gumall.product.entity.CategoryEntity;
import cn.jcet.gumall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        // 查询全部
        List<CategoryEntity> entities = this.baseMapper.selectList(null);

        // 使用stream流式计算
        List<CategoryEntity> levelMenus = entities.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .map(menu -> {
                    menu.setChildren(getChildrens(menu,entities));
                    return menu;
                })
                .sorted((menu1,menu2)->{
                    return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                })
                .collect(Collectors.toList());

        return levelMenus;
    }

    @Override
    public void removeMenusByIds(List<Long> longs) {
        // TODO: 2020/7/4  菜单是否关联其他所用到的地方

        // 删除
        this.baseMapper.deleteBatchIds(longs);
    }

    @Override
    public Long[] findByCateLogPath(Long cateLogId) {
        List<Long> path = new ArrayList<>();
        List<Long> parentPath = this.findParentPath(cateLogId, path);
        // 反转
        Collections.reverse(parentPath);

        return parentPath.toArray(new Long[parentPath.size()]);
    }

    @Override
    public void updateDetail(CategoryEntity category) {
        this.updateById(category);
        // 同步更新，更具id
        if (!StringUtils.isEmpty(category.getName())){
            // 同步更新冗余表中数据
            categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
        }
    }

    private List<Long> findParentPath(Long cateLogId,List<Long> paths){
        paths.add(cateLogId);
        // 根据id查询
        CategoryEntity entity = this.getById(cateLogId);
        if (null != entity){
            if (entity.getParentCid() != 0){
                // 自己调用自己，知道最后一个节点
                findParentPath(entity.getParentCid(),paths);
            }
        }
        return paths;
    }

    /**
     * 获取子菜单
     * @param root
     * @param all
     * @return
     */
    private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> all){
        List<CategoryEntity> entities = all.stream()
                .filter(categoryEntity -> {
                    //  父级菜单和分类类别进行对比
                    return categoryEntity.getParentCid().equals(root.getCatId());
                })
                .map(categoryEntity -> {
                    // 获取子菜单，列表的全部子菜单，并且返回
                    categoryEntity.setChildren(getChildrens(categoryEntity, all));
                    return categoryEntity;
                })
                .sorted((menu1, menu2) -> {
                    // 排序字段进行排序比较
                    return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                })
                // 返回一个list集合列表
                .collect(Collectors.toList());

        return entities;
    }

}